import configparser
import os
from typing import Dict, List
from utils.logger import get_logger

logger = get_logger("error_codes.py+ErrorCodeLoader")

class ErrorCodeLoader:
    """错误码加载器"""
    
    def __init__(self, config_path: str = "config/errorcodes.ini"):
        self.config_path = config_path
        self.error_codes: Dict[int, str] = {}
        self._load_error_codes()
        
    def _load_error_codes(self):
        """加载错误码配置文件"""
        try:
            if not os.path.exists(self.config_path):
                logger.warning(f"Error codes config file not found: {self.config_path}")
                return
                
            config = configparser.ConfigParser()
            config.read(self.config_path, encoding='utf-8')
            
            if 'Error' in config:
                for code, message in config['Error'].items():
                    try:
                        self.error_codes[int(code)] = message
                    except ValueError:
                        logger.warning(f"Invalid error code format: {code}")
                        
            logger.info(f"Loaded {len(self.error_codes)} error codes from {self.config_path}")
        except Exception as e:
            logger.error(f"Failed to load error codes: {e}")
            
    def get_error_message(self, code: int) -> str:
        """根据错误码获取错误信息"""
        return self.error_codes.get(code, f"未知错误码: {code}")
        
    def format_fault_codes(self, codes: List[int]) -> str:
        """格式化故障码列表"""
        if not codes:
            return ""
            
        formatted_codes = []
        for i, code in enumerate(codes, 1):
            message = self.get_error_message(code)
            formatted_codes.append(f"{i}.{code}.{message}")
            
        return ",".join(formatted_codes)